import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { ArticleEntity } from './article.entity';
import { TagEntity } from '../tag/tag.entity';
@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(ArticleEntity)
    private articleRepository: Repository<ArticleEntity>,
    @InjectRepository(TagEntity)
    private tagRepository: Repository<TagEntity>,
  ) {}
  // 增加
  async create(createArticleDto: any): Promise<any> {
    const { tags } = createArticleDto;
    // new一个文章
    let newArticle: ArticleEntity = new ArticleEntity();
    newArticle = createArticleDto;
    newArticle.tags = [];
    // 多个标签遍历
    for (let index = 0; index < tags.length; index++) {
      const tag = tags[index];
      let newTag: TagEntity = null;

      // 如果tag存在就不新增
      let resTag = await this.tagRepository.findOneBy({
        name: tag,
      });
      // .createQueryBuilder()
      // .where([{ name: tag }])
      // .getOne();
      if (resTag) {
        newTag = resTag;
      } else {
        newTag = new TagEntity();
        newTag.name = tag;
        await this.tagRepository.save(newTag);
      }
      newArticle.tags.push(newTag);
    }
    // 新增 删除id
    delete createArticleDto.id;
    // 新增账号
    return await this.articleRepository.save(newArticle);
  }

  // 软删除
  async delete(removeUserDto: any): Promise<any> {
    const { ids } = removeUserDto;
    return this.articleRepository.softDelete(ids);
  }
  //   查详情
  async findOne(id: string): Promise<any> {
    let res = await this.articleRepository
      .createQueryBuilder('user')
      .where([{ id: id }])
      .leftJoinAndSelect('user.info', 'id')
      .getOne();
    //   .getMany();
    //   .getOne();

    console.log(res);
    return res;
  }

  // 更新
  async update(updateUserData: any): Promise<any> {
    const { id, updateUserDto } = updateUserData;
    // // updateUserDto.updatedAt = new Date();
    // const { name } = updateUserDto;

    // const isExist = await this.articleRepository.count({
    //   where: {
    //     name,
    //   },
    // });
    // if (isExist > 1) {
    //   return {
    //     statusCode: 201,
    //     message: '已存在',
    //   };
    // }
    return await this.articleRepository.update(id, updateUserDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, page = 1, limit = 10 } = query;
    const skip = (page - 1) * limit;

    let params = {
      skip,
      take: limit,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    params = Object.assign(
      {
        select: ['id', 'title', 'content', 'desc', 'views', 'updated_at'],
      },
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updated_at: 'DESC',
        },
      },
      { relations: ['tags'] },
      { leftJoin: ['tags.name'] },
    );
    // throw new HttpException('文章已存在', 401);
    // const [data, total] = await this.articleRepository.createQueryBuilder("user")
    // .leftJoinAndSelect("user.info", "info")
    // .getMany();
    const res = await this.articleRepository.findAndCount(params);
    // .findAndCount(params);
    // .getMany();
    //
    return res;
  }
}
